package com.atguigu.day04;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

//关于callable的练习
class callable1 implements Callable<Integer> {
    @Override
    //重写call方法
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName()+"\t"+"callable,,,come in ...");
        //线程睡眠几秒
//        try {
//            TimeUnit.SECONDS.sleep(3);} catch (InterruptedException e) {throw new RuntimeException(e);}
        return 555;
    }
}
//重写run方法
class runnable2 implements Runnable{
    @Override
    public void run() {
        System.out.println("runable...come in ...");
    }
}
public class CallableDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        FutureTask<Integer> futureTask = new FutureTask<>(new callable1());
//        FutureTask futureTask = new FutureTask<Integer>(new Callable<Integer>() {
//            @Override
//            public Integer call() throws Exception {
//                System.out.println("callable ....come in...");
//                return 666;
//            }
//        });
        System.out.println("-============================");
        FutureTask futureTask =  new FutureTask(()->{
            System.out.println("callable ....come in...");
            return 999;
        });
//                FutureTask futureTask =  new FutureTask(()->999);


        new Thread(futureTask,"A").start();
        new Thread(futureTask,"B").start();//虽然有两个线程，但是callable，，，come in只打印一次。
        //只计算一次，第二次复用第一次的结果(如果多个线程，访问一个futureTask，只会算一次，后面的结果直接复用)

        System.out.println(Thread.currentThread().getName()+"\t"+"main...over");

        System.out.println(futureTask.get());   //get必须放在最后，否则下面的打印将会跟该方法一起等待
        System.out.println(futureTask.get());

        System.out.println(futureTask.isDone());
    }


}
